import sys
import shutil
import datetime
import pytz

import common

# add the project library folder
sys.path.append("lib/")

import shapefile

def loadCountyList():
    # load OKC county list

    kounCountyLoc = {}
    kounCountyCodes = {}
    kounCountiesVis = []
    kounCounties = {}
    
    fCountyLoc = open('%s/county-locations.txt'%common.WarningDir, 'r')
    fCountyCodes = open('%s/county-list.txt'%common.WarningDir, 'r')
    fCountiesVis = open('%s/visible-counties.txt'%common.WarningDir, 'r')

    # load the county locations...
    for line in fCountyLoc:
        if line[0:2] != "OK":
            continue

        # the lines all have 'county' at the end
        name = line[7:line.find('County')].strip().lower()
        lat = float(line[142:151].strip())
        lon = float(line[151:].strip())
        kounCountyLoc[name] = (lat, lon)

    # and the correct NWS codes...
    for line in fCountyCodes:
        line = line.strip()
        lineParts = line.split('\t')
        code = int(lineParts[1].strip())
        name = lineParts[0].strip()
        kounCountyCodes[name.lower()] = code

    # and which ones are visible on the KTLX radar...
    for line in fCountiesVis:
        kounCountiesVis.append(line.strip().lower())

    # make the final dictionary with keys = codes, values = name, lat, lon
    for c in kounCountiesVis:
        code = kounCountyCodes[c]
        lat, lon = kounCountyLoc[c]
        kounCounties[code] = (c, lat, lon)

    return kounCounties

def loadTorWarnings(years):
    kounCounties = loadCountyList()

    # load OKC warnings
    tor_warn = []

    utc = pytz.utc
    
    for year in years:
        sf = shapefile.Reader("%s/wwa_%d01010000_%d01010000"%(common.WarningDir, year, year+1))
        records = sf.records()
        for rec in records:
            #issued
            iYear = int(rec[1][0:4])
            iMon = int(rec[1][4:6])
            iDay = int(rec[1][6:8])
            iHour = int(rec[1][8:10])
            iMin = int(rec[1][10:12])
            iTime = utc.localize(datetime.datetime(iYear, iMon, iDay,
                                      iHour, iMin))

            # expired
            eYear = int(rec[2][0:4])
            eMon = int(rec[2][4:6])
            eDay = int(rec[2][6:8])
            eHour = int(rec[2][8:10])
            eMin = int(rec[2][10:12])
            eTime = utc.localize(datetime.datetime(eYear, eMon, eDay,
                                      eHour, eMin))

            # some of the ugc data seems to be corrupted... must filter
            # for state here...
            ugcState = rec[8][0:2]
            if ugcState == "OK":
                ugcCounty = int(rec[8][3:6])

                if ugcCounty in kounCounties.keys():
                    warning = {"station":rec[0],
                               "iTime":iTime,
                               "eTime":eTime,
                               "phenom":rec[3],
                               "type":rec[4],
                                "etn":rec[6],
                               "status":rec[7],
                               "state":ugcState,
                               "countyCode":ugcCounty,
                               "countyName":kounCounties[ugcCounty][0],
                               "countyLatLon":(kounCounties[ugcCounty][1], kounCounties[ugcCounty][2])}
                    if warning["station"] == "OUN" and \
                        warning["phenom"] == "TO":
                        tor_warn.append(warning)
	# sort by time
	tor_warn.sort(key = lambda x:x['iTime'])
    return tor_warn

